var DataSource = function () {

    var self = this;
    this.$grid_selector = $("#datasource-grid-table");
    this.pager_selector = "#datasource-grid-pager";
    // 请求url
    this.URL = {
        ADD: '/report/datasource/add',
        TEST: '/report/datasource/connection/test',
        EDIT: '/report/datasource/edit',
        DEL: '/report/datasource/del'
    };
    // 数据库类型
    this.databaseType = {
        '10': 'postgresql',
        '11': 'mysql'
    };
    // 连接池类型
    this.poolType = {
        '10': 'c3p0',
        '11': 'druid'
    };
    // 默认url
    this.jdbcUrl = {
        '10': 'jdbc:postgresql://127.0.0.1:5432/report_system?characterEncoding=UTF-8&amp;useSSL=false',
        '11': 'jdbc:mysql://127.0.0.1:3306/database?characterEncoding=UTF-8&amp;useSSL=false'
    };
    // 数据库对应驱动类
    this.driverClass = {
        '10': 'org.postgresql.Driver',
        '11': 'com.mysql.jdbc.Driver'
    };
    this.colModel = [
        {name: 'rdsId', width: 10, editable: true, key: true},
        {name: 'name', width: 30, editable: true},
        {name: 'username', hidden: true, editable: true},
        {name: 'password', hidden: true, editable: true},
        {
            name: 'jdbcUrl',
            editable: true,
            editoptions: {
                size: "40",
                maxlength: "30",
                defaultValue: 'jdbc:postgresql://192.168.99.100:5432/report_system?useSSL=false'
            }
        },
        {name: 'driverClass', width: 50, editable: true},
        {
            name: 'databaseType', width: 30, editable: true, formatter: function (cell, row) {
                return self.databaseType[cell];
            }, unformat: function (cell) {
                _.each(self.databaseType, function (value, key) {
                    if (value === cell) cell = key;
                });
                return cell;
            }
        },
        {
            name: 'poolType', width: 30, editable: true, formatter: function (cell, row) {
                return self.poolType[cell];
            }, unformat: function (cell) {
                _.each(self.poolType, function (value, key) {
                    if (value === cell) cell = key;
                });
                return cell;
            }
        },
        {
            name: 'createdAt', width: 50, formatter: "date",
            formatoptions: {srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s'}
        }
    ];
    this.options = {
        moduleKey: 'report/datasource',
        pager: this.pager_selector,
        sortname: 'rdsId',
        caption: "数据源列表",
        colNames: ['ID', '名称', '用户名', '密码', 'JDBC URL', '驱动类', '数据库', '连接池', '创建时间'],
        colModel: this.colModel,
        navbarDefaultIcon: {
            del: false,
            add: false,
            edit: false,
            view: false,
            search: false
        }
    };
    this.template = _.template('<form id="form_add" style="padding: 16px;" class="form-horizontal" method="post">\
                                <input id="driverClass" name="driverClass" value="{{driverClass}}" hidden="hidden">\
                                <input id="rdsId" name="rdsId" value="{{rdsId}}" hidden="hidden">\
                                <div class="form-group">\
                                    <label for="name" class="col-xs-1 control-label">名称</label>\
                                    <div class="col-xs-11"><input class="form-control" type="text" name="name" id="name" value="{{name}}"></div>\
                                </div>\
                                <div class="form-group">\
                                    <label for="username" class="col-xs-1 control-label">用户</label>\
                                    <div class="col-xs-5"><input class="form-control" type="text" name="username" id="username" value="{{username}}"></div>\
                                    <label for="password" class="col-xs-1 control-label">密码</label>\
                                    <div class="col-xs-5"><input autocomplete="off" type="password" class="form-control" name="password" id="password" value="{{password}}"></div>\
                                </div>\
                                <div class="form-group">\
                                    <label for="databaseType" class="col-xs-1 control-label">数据源</label>\
                                    <div class="col-xs-5">\
                                        <select class="form-control" name="databaseType" id="databaseType">\
                                        {{databaseType}}\
                                        </select>\
                                    </div>\
                                    <label for="poolType" class="col-xs-1 control-label">连接池</label>\
                                    <div class="col-xs-5">\
                                        <select class="form-control" name="poolType" id="poolType">\
                                        {{poolType}}\
                                        </select>\
                                    </div>\
                                </div>\
                                <div class="form-group">\
                                    <label for="jdbcUrl" class="col-xs-1 control-label">jdbcUrl</label>\
                                    <div class="col-xs-11"><input class="form-control" type="text" name="jdbcUrl" id="jdbcUrl" value="{{jdbcUrl}}"></div>\
                                </div>\
                             </form>');
};

DataSource.prototype = {
    // 初始化表格
    initGird: function () {

        var self = this;
        this.$grid_selector
            .xumf_jqGird(this.options)
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "删除",
                buttonicon: "fa fa-trash-o red",
                onClickButton: function () {
                    $(this).getGridSelectedRow(function (rowData) {
                        self.delUI(rowData.rdsId)
                    });
                },
                position: "first"
            })
            // 编辑按钮初始化
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "编辑",
                buttonicon: "fa fa-pencil blue",
                onClickButton: function () {
                    self.editUI();
                },
                position: "first"
            })
        // 添加按钮初始化
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "添加",
                buttonicon: "fa fa-plus-circle purple",
                onClickButton: function () {
                    self.addUI();
                },
                position: "first"
            })
    },
    /**
     * 生产编辑模版
     * @returns {*} 模版
     */
    generateEditTemplate: function (rowData) {
        rowData.databaseType = _.chain(this.databaseType)
            .map(function (value, key) {
                return _.template('<option {{selected}} value="{{key}}">{{value}}</option>')({
                    key: key,
                    value: value,
                    selected: key === rowData.databaseType ? 'selected' : ''
                })
            })
            .reduce(function (a, b) {
                return a + b;
            }).value();
        rowData.poolType = _.chain(this.poolType)
            .map(function (value, key) {
                return _.template('<option {{selected}} value="{{key}}">{{value}}</option>')({
                    key: key,
                    value: value,
                    selected: key === rowData.poolType ? 'selected' : ''
                })
            })
            .reduce(function (a, b) {
                return a + b;
            }).value();
        return this.template(rowData);
    },
    delUI: function (rdsId) {
        var $grid_selector = this.$grid_selector;
        var self = this;
        $.xumf.confirm('删除所选记录？', function (index, layero) {
            $.xumf.ajaxAndLoading({
                url: self.URL.DEL,
                data: {id: rdsId}
            }).done(function (res) {
                layer.close(index);
                res.success && $grid_selector.trigger("reloadGrid")
            });
        });
    },
    /**
     * 编辑dialog初始化
     */
    editUI: function () {

        var self = this;
        var rowId = this.$grid_selector.xumf_jqGird('getGridParam', 'selrow');
        if (null === rowId) {
            $.xumf.gritterError('请选择行');
        } else {
            var rowData = this.$grid_selector.xumf_jqGird('getRowData', rowId);
            // 显示弹框
            layer.open({
                title: '编辑数据源',
                area: ['50%', '350px'],
                content: this.generateEditTemplate(rowData),
                btn: ['测试连接', '确定', '取消'],
                btn1: function (index, layero) {
                    return self.testConnectionAction();
                },
                btn2: function (index, layero) {
                    self.editAction() && layer.close(index);
                },
                success: function (layero, index) {
                    var $databaseType = $('#databaseType');
                    // 绑定change事件，根据数据源类型，更改jdbc url
                    $databaseType.on('change', function (event) {
                        var databaseType = $(event.currentTarget).val();
                        $('#driverClass').val(self.driverClass[databaseType]);
                        $('#jdbcUrl').val(self.jdbcUrl[databaseType]);
                        event.preventDefault();
                    });
                }
            });
        }
    },
    /**
     * 添加dialog初始化
     */
    addUI: function () {

        var self = this;
        // 显示弹框
        layer.open({
            title: '添加数据源',
            area: ['50%', '350px'],
            content: this.generateEditTemplate({
                driverClass: '',
                username: '',
                password: '',
                name: '',
                databaseType: '',
                poolType: '',
                rdsId: '',
                jdbcUrl: ''
            }),
            btn: ['测试连接', '确定', '取消'],
            btn1: function (index, layero) {
                return self.testConnectionAction();
            },
            btn2: function (index, layero) {
                self.addAction() && layer.close(index);
            },
            success: function (layero, index) {
                var $databaseType = $('#databaseType');
                // 绑定change事件，根据数据源类型，更改jdbc url
                $databaseType.on('change', function (event) {
                    var databaseType = $(event.currentTarget).val();
                    $('#driverClass').val(self.driverClass[databaseType]);
                    $('#jdbcUrl').val(self.jdbcUrl[databaseType]);
                    event.preventDefault();
                });
                $databaseType.trigger('change');
            }
        });
    },
    /**
     * 测试操作
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    testConnectionAction: function () {
        // 提交事件
        var $form = $('#form_add');
        $form.attr('action', this.URL.TEST);
        this.validateAction($form);
        // 阻止dialog消失
        return false;
    },
    /**
     * 添加操作
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    addAction: function () {
        var $form = $('#form_add');
        $form.attr('action', this.URL.ADD);
        return this.validateAction($form);
    },
    /**
     * 编辑操作
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    editAction: function () {
        var $form = $('#form_add');
        $form.attr('action', this.URL.EDIT);
        return this.validateAction($form);

    },
    /**
     * 验证与提交
     * @param $form 表单的jquery对象
     * @returns {*} 验证是否成功
     */
    validateAction: function ($form) {
        var $grid_selector = this.$grid_selector;
        $form.validate({
            rules: {
                name: {required: true},
                username: {required: true},
                password: {required: true},
                databaseType: {required: true},
                poolType: {required: true},
                jdbcUrl: {required: true},
                driverClass: {required: true}
            },
            errorElement: "em"
        });
        // 验证成功
        var valid = $form.valid();
        if (valid) {
            $.xumf.showLoading();
            $form.ajaxSubmit({
                success: function (res) {
                    $.xumf.hideLoading();
                    $.xumf.gritter(res);
                    res.success && $grid_selector.trigger("reloadGrid")
                }
            });
        }
        return valid;
    }
};



